package com.demo.bmsconsole;

import java.io.BufferedOutputStream;
import java.util.Calendar;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import android.content.Context;
import android.os.Handler;
import android.util.Log;
import android.widget.TextView;

public class LogFile {
	private Context mCtx;
	private static String TAG;
	private static final String mLogFileDir = "/sdcard/logs/";
    private static SimpleDateFormat mLogDateFormat = new SimpleDateFormat("HH:mm:ss");
    private static SimpleDateFormat mLogFileDateFormat = new SimpleDateFormat("yyyy-MM-dd");
	private String mLogFileName;
	private static OutputStream mLogFileStream = null;
	private static Handler mHandler = new Handler();

	LogFile(Context ctx)
	{
		mCtx = ctx;
		TAG = mCtx.getPackageName();
		initialize();
	}

	public static void close() throws IOException
	{
		if (mLogFileStream != null)
			mLogFileStream.close();
	}
	private void initialize()
	{
		setLogFile();
	}

	private void setLogFile()
	{
        mLogFileName = mLogFileDir + mLogFileDateFormat.format(Calendar.getInstance().getTime()) + ".log";
        mLogFileStream = null;
        try {
        	mLogFileStream = new BufferedOutputStream(new FileOutputStream(mLogFileName, true));
        	mLogFileStream.write(new String("\n==> Starting New LogFile <==\n").getBytes());
		} catch (Exception e) {
			mLogFileStream = null;
			BMSconsole.log("Can't write LOG file.");
		}
	}

	public static String now() {
		return mLogDateFormat.format(Calendar.getInstance().getTime());
	}
	public static void log(final String text) {
		if (mLogFileStream == null) {
			BMSconsole.log(text);
			return;
		}
		mHandler.post(new Runnable() {
			public void run() {
				if (mLogFileStream == null) {
					Log.d(TAG, now() + text);
				}
				try {
					mLogFileStream.write(new String(now() + " " + text+"\n").getBytes());
				} catch (IOException e) {
					Log.e(TAG,"writing to LogFile" + e.toString());
				}
			}
		});
	}
	

}
